import {_decorator, Component, Node, Button, Label, instantiate, Prefab} from 'cc';

const {ccclass, property} = _decorator;

enum GameState {
    GS_INIT,
    GS_PLAYING,
    GS_END,
};

@ccclass('GameManager')
export class GameManager extends Component {


    @property({type: Label})
    public num1Label: Label | null = null;
    @property({type: Label})
    public num2Label: Label | null = null;
    @property({type: Label})
    public num3Label: Label | null = null;
    @property({type: Label})
    public num4Label: Label | null = null;
    @property({type: Prefab})
    public labelPrfb: Prefab | null = null;
    @property({type: Node})
    public resultView: Node | null = null;
    @property({type: Node})
    public startMenu: Node | null = null;
    @property({type: Node})
    public mainPage: Node | null = null;

    // 是否接收到确定指令
    private _isOk: boolean = false;
    private _resultList: string[] = [];
    private _currentrResult = null;
    private _numIndex = 0;
    private _trueNumber = "";
    private numberList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

    onLoad(){

    }


    start() {
        this.curState = GameState.GS_INIT;
        //@ts-ignore
        if (typeof wx === 'undefined') {
            return;
        }
        //@ts-ignore
        wx.showShareMenu({
            menus: ['shareAppMessage', 'shareTimeline'],
            success: (res) => {
                console.log('开启被动转发成功！');
            },
            fail: (res) => {
                console.log(res);
                console.log('开启被动转发失败！');
            }
        });
    }

    update(deltaTime: number) {
        if (this._isOk) {
            this.toReturnResult();
        }
    }

    set curState(value: GameState) {
        switch (value) {
            case GameState.GS_INIT:
                this.init();
                break;
            case GameState.GS_PLAYING:
                if (this.startMenu) {
                    this.startMenu.active = false;
                }
                if (this.mainPage) {
                    this.mainPage.active = true;
                }

                break;
            case GameState.GS_END:
                break;
        }
    }

    init() {
        if (this.startMenu) {
            this.startMenu.active = true
        }
        if (this.mainPage) {
            this.mainPage.active = false
        }
        this._isOk = false;
        this._resultList = [];
        this.resultView.removeAllChildren();
        this.initNum();
        this.toGenerateTrueNumber();
    }

    initNum() {
        this._numIndex = 0;
        this.num1Label.string = 'N/A';
        this.num2Label.string = 'N/A';
        this.num3Label.string = 'N/A';
        this.num4Label.string = 'N/A';
    }

    toGenerateTrueNumber() {
        let num = "";
        let numberList = this.numberList.slice();
        for (let i = 0; i < 4; i++) {
            let index = Math.floor(Math.random() * numberList.length);
            console.info("trueNumber index:", index)
            num = num + numberList[index]
            numberList.splice(index, 1);
        }
        console.info("trueNumber:", num)
        this._trueNumber = num;
    }

    guess(val) {
        let reuslt = "";
        let trueNumberArr = this._trueNumber.split("")
        let guessNumberArr = val.split("")
        let a_num = 0
        let b_num = 0
        for (let i = 0; i < 4; i++) {
            if (parseInt(trueNumberArr[i]) == parseInt(guessNumberArr[i])) {
                a_num++
            } else if (this._trueNumber.indexOf(guessNumberArr[i]) != -1) {
                b_num++
            }
        }
        reuslt = a_num + "A" + b_num + "B"
        return reuslt
    }

    /**
     *  返回结果
     * */
    toReturnResult() {
        this._resultList.push(this._currentrResult);
        let node = instantiate(this.labelPrfb);
        let tmpLabel = node.getComponent(Label)
        tmpLabel.string = this._currentrResult
        tmpLabel.fontSize  = 40
        this.resultView.addChild(node)
        this.initNum();
        this._isOk = false;
        if (this._resultList.length >= 8) {
            this.curState = GameState.GS_INIT;
            return
        }
    }

    onKeyboardButtonClicked(event: Event, customEventData: string) {
        if (customEventData === "?") {

        } else if (customEventData === "ok") {
            if (this.num1Label.string === 'N/A'
                || this.num2Label.string === 'N/A'
                || this.num3Label.string === 'N/A'
                || this.num4Label.string === 'N/A'
            ) {
                return
            }

            let num = this.num1Label.string + this.num2Label.string + this.num3Label.string + this.num4Label.string
            let result = this.guess(num)
            if (result === '4A0B') {
                console.info("game win!")
                this.curState = GameState.GS_INIT;
                return
            }
            this._currentrResult = this._resultList.length + 1 + "、" + num + " " + result;
            this._isOk = true;

        } else {
            let has = false;
            has = this.checkHas(customEventData)
            if (has) {
                return
            }
            switch (this._numIndex) {
                case 0:
                    if (this.num1Label) {
                        this.num1Label.string = customEventData;
                    }
                    break;
                case 1:
                    if (this.num2Label) {
                        this.num2Label.string = customEventData;
                    }
                    break;
                case 2:
                    if (this.num3Label) {
                        this.num3Label.string = customEventData;
                    }
                    break;
                case 3:
                    if (this.num4Label) {
                        this.num4Label.string = customEventData;
                    }
                    break;
                default:
                    break
            }
            if (this._numIndex < 3) {
                this._numIndex++;
            }
        }
        console.info("onKeyboardButtonClicked：", customEventData)
    }

    checkHas(val) {
        if (this.num1Label.string === val) {
            return true;
        }
        if (this.num2Label.string === val) {
            return true;
        }
        if (this.num3Label.string === val) {
            return true;
        }
        if (this.num4Label.string === val) {
            return true;
        }
        return false
    }

    onNumPositionClicked(event: Event, customEventData: string) {
        if (customEventData === '0') {
            this._numIndex = 0;
        } else if (customEventData === '1') {
            this._numIndex = 1
        } else if (customEventData === '2') {
            this._numIndex = 2;
        } else if (customEventData === '3') {
            this._numIndex = 3;
        }
        console.info("onNumPositionClicked：", customEventData)
    }

    onStartButtonClicked() {
        this.curState = GameState.GS_PLAYING;
    }

    onShareClicked(){
        //@ts-ignore
        if (typeof wx === 'undefined') {
            return;
        }
        //@ts-ignore
        wx.shareAppMessage({
            title: '这里写分享卡片的标题',
            // imageUrl: cc.url.raw('img.png'),        // 分享图片要放在 wechatgame/res/raw-assers 路径下
            query: 'shareMsg='+'分享卡片上所带的信息'  // query最大长度(length)为2048
        });
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/zh/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/zh/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/zh/scripting/life-cycle-callbacks.html
 */
